package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.service.ISeckillGoodService;
import cn.wolfcode.shop.util.RedisKeys;
import cn.wolfcode.shop.vo.SeckillGoodVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("api/seckillGoods")
public class SeckillGoodController {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/query")
    public Result<List<SeckillGoodVO>> query() {
        return Result.success(seckillGoodService.query());
    }

    @RequestMapping("/findById")
    public Result<SeckillGoodVO> findById(Long seckillGoodId) {
        return Result.success(seckillGoodService.findById(seckillGoodId));
    }

    // 模拟创建秒杀活动，然后进行 热点数据 预热
    @RequestMapping("/initData")
    public Result<String> initData() {
        // 先从数据库中查到数据，然后存储进redis中
        List<SeckillGoodVO> list = seckillGoodService.query();  // 这不一个等同于listAll的方法，没有实现高查
        for (SeckillGoodVO vo : list) {
            // 将库存数据保存进 Redis 的 Hash 中
            redisTemplate.opsForHash().put(RedisKeys.SECKILL_GOOD_STOCKCOUNT_HASH.join(),
                                        vo.getId() + "",
                                        vo.getGoodStock() + "");

            // 将秒杀商品信息保存进 Redis 的 Hash 中
            redisTemplate.opsForHash().put(RedisKeys.SECKILL_GOOD_HASH.join(),
                                        vo.getId() + "",
                                        JSON.toJSONString(vo));
        }
        return Result.success("sunccess");
    }


}
